<template>
  <div id="manageUserView">
    <a-form
      :model="searchParams"
      layout="inline"
      style="display: flex; flex-wrap: wrap"
    >
      <a-form-item field="userName" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.userName" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">提交</a-button>
      </a-form-item>
      <a-form-item style="margin-left: auto">
        <a-button status="warning" @click="handleClick">新增</a-button>
        <a-modal
          v-model:visible="visible"
          title="新增用户"
          @cancel="handleCancel"
          @ok="doAdd"
        >
          <a-form :model="form" style="width: 400px">
            <a-form-item field="userName" label="用户昵称">
              <a-input v-model="form.userName" />
            </a-form-item>
            <a-form-item field="userAccount" label="账号">
              <a-input v-model="form.userAccount" />
            </a-form-item>
            <a-form-item field="userPassword" label="密码">
              <a-input v-model="form.userPassword" />
            </a-form-item>
            <a-form-item field="stuId" label="学号">
              <a-input v-model="form.stuId" />
            </a-form-item>
            <a-form-item field="stuClass" label="班级">
              <a-input v-model="form.stuClass" />
            </a-form-item>
            <a-form-item field="userProfile" label="简介">
              <a-input v-model="form.userProfile" />
            </a-form-item>
            <a-form-item field="userRole" label="角色">
              <a-select v-model="form.userRole">
                <a-option value="user">用户</a-option>
                <a-option value="admin">管理员</a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-modal>
        <a-popconfirm
          content="确定删除吗?"
          okText="确定"
          cancelText="取消"
          type="error"
          @ok="doBatchDelete"
        >
          <a-button status="danger" style="margin-left: 10px"
            >批量删除</a-button
          >
        </a-popconfirm>
      </a-form-item>
    </a-form>
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="handleClick2(record)">修改</a-button>
          <a-modal
            v-model:visible="visible2"
            title="修改用户"
            @cancel="handleCancel2"
            @ok="doUpdate"
          >
            <a-form :model="form" style="width: 400px">
              <a-form-item field="userName" label="用户昵称">
                <a-input v-model="form.userName" />
              </a-form-item>
              <a-form-item field="userAccount" label="账号">
                <a-input v-model="form.userAccount" />
              </a-form-item>
              <a-form-item field="userPassword" label="密码">
                <a-input v-model="form.userPassword" />
              </a-form-item>
              <a-form-item field="stuId" label="学号">
                <a-input v-model="form.stuId" />
              </a-form-item>
              <a-form-item field="stuClass" label="班级">
                <a-input v-model="form.stuClass" />
              </a-form-item>
              <a-form-item field="userProfile" label="简介">
                <a-input v-model="form.userProfile" />
              </a-form-item>
              <a-form-item field="userRole" label="角色">
                <a-select v-model="form.userRole">
                  <a-option value="user">用户</a-option>
                  <a-option value="admin">管理员</a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-modal>
          <a-popconfirm
            content="确定删除吗?"
            okText="确定"
            cancelText="取消"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button status="danger">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
  User,
  UserControllerService,
  UserQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import * as querystring from "querystring";
import { useRouter } from "vue-router";

const tableRef = ref();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref<UserQueryRequest>({
  userName: "",
  userRole: "",
  pageSize: 10,
  current: 1,
});
const selectedKeys = ref([]);

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
});

const visible = ref(false);
const visible2 = ref(false);
const form = reactive({
  id: "",
  userName: "",
  userAccount: "",
  userPassword: "",
  stuId: "",
  stuClass: "",
  userProfile: "",
  userRole: "",
});

const handleClick = () => {
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  visible.value = true;
};

const handleClick2 = (user: User) => {
  visible2.value = true;
  Object.keys(user).forEach((key) => {
    form[key] = user[key];
  });
};

const handleCancel = () => {
  visible.value = false;
};
const handleCancel2 = () => {
  visible2.value = false;
};
/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

const loadData = async () => {
  const res = await UserControllerService.listUserByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

// {id: "1", title: "A+ D", content: "新的题目内容", tags: "["二叉树"]", answer: "新的答案", submitNum: 0,…}

const columns = [
  {
    title: "id",
    dataIndex: "id",
    width: 250,
  },
  {
    title: "用户昵称",
    dataIndex: "userName",
  },
  {
    title: "账号",
    dataIndex: "userAccount",
  },
  {
    title: "学号",
    dataIndex: "stuId",
  },
  {
    title: "班级",
    dataIndex: "stuClass",
  },
  {
    title: "用户简介",
    dataIndex: "userProfile",
  },
  {
    title: "角色",
    dataIndex: "userRole",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const doDelete = async (user: User) => {
  const res = await UserControllerService.deleteUserUsingPost({
    ids: [user.id],
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};
const doBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    message.error("未选数据");
    return;
  }
  const res = await UserControllerService.deleteUserUsingPost({
    ids: selectedKeys.value,
  });
  if (res.code === 0) {
    message.success("删除成功");
    await loadData();
  } else {
    message.error("删除失败");
  }
};

const router = useRouter();

const doAdd = async () => {
  const res = await UserControllerService.addUserUsingPost(form);
  if (res.code === 0) {
    message.success("添加成功");
    await loadData();
  } else {
    message.error("添加失败");
  }
};

const doUpdate = async () => {
  const res = await UserControllerService.updateUserUsingPost(form);
  if (res.code === 0) {
    message.success("添加成功");
    await loadData();
  } else {
    message.error("添加失败");
  }
  return;
};
</script>

<style scoped>
#manageUserView {
  max-width: 1200px;
  margin: 0 auto;
}
</style>
